<template>
  <go-back />
  <div class="title">修改问卷内容</div>
  <a-spin :spinning="spinning" tip="修改成功，正在跳转页面...">
    <paper-top :paper="paper" isType="edit" @changeTitle="changeTitle" @changeStatus="changeStatus" @changeStartTime="changeStartTime" @changeEndTime="changeEndTime" />
    <div v-for="(questionsItem, index) in paper.questions" :key="index" class="content">
      <questions-item :index="index" :questionsItem="questionsItem" :itemLength="paper.questions.length" @addQuestion="addQuestion" @deleteQuestion="deleteQuestion" />
    </div>
    <div class="bottom">
      <a-button type="primary" size="large" @click="publishPaper" block style="height: 40px; margin: 0 20px; width: 97%">修改问卷</a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode, defineComponent, ref, toRaw, reactive, onMounted, watch } from 'vue'
import PaperTop from '../../../components/paperTop.vue'
import QuestionsItem from '../../../components/questionSetting.vue'
import GoBack from '../../../components/goback.vue'
import { useRouter, useRoute } from 'vue-router'
import { Modal, message } from 'ant-design-vue'
import { detele, get, put } from '../../../utils/request/request'

interface PaperData {
  title: string
  start_time: string
  end_time: string
  status: number | undefined
  questions: {
    number: number | undefined
    is_require: boolean
    questionType: number
    questionTitle: string
    questionOption: string[] | never[]
  }[]
}

interface QuestionsItems {
  number: number | undefined
  is_require: boolean
  questionType: number
  questionTitle: string
  questionOption: string[] | never[]
}

// PaperTop子组件调用父组件方法
const useChangeEffect = (paper: PaperData) => {
  const changeTitle = (title: string) => {
    paper.title = title
  }
  const changeStatus = (status: number) => {
    paper.status = status
  }
  const changeStartTime = (start_time: string) => {
    paper.start_time = start_time
  }
  const changeEndTime = (end_time: string) => {
    paper.end_time = end_time
  }
  return {
    changeTitle,
    changeStatus,
    changeStartTime,
    changeEndTime
  }
}

// 增删组件相关逻辑
const useEmitEffect = (paper: PaperData, token: string) => {
  const addQuestion = (index: number) => {
    const newItem: QuestionsItems = {
      number: undefined, //题号
      is_require: true, //是否必填
      questionType: 1, //问题类型：1.单选题 2.多选题 3.填空题
      questionTitle: '', //问题描述
      questionOption: ['', ''] //问题选项，填空题无元素，选择题必须包含两个以上元素
    }
    paper.questions.splice(index + 1, 0, newItem)
  }
  const deleteQuestion = async (index: number, id: number) => {
    // console.log(index,id);
    if (id) {
      const res: any = await detele(`/admin/api/v1/paper/question/${id}`, {}, token)
      console.log(res)
      if (res.code === 0) {
        if (res.data.result === 0) {
          paper.questions.splice(index, 1)
        } else {
          message.error('删除失败')
        }
      }
    } else {
      paper.questions.splice(index, 1)
    }
  }
  return {
    addQuestion,
    deleteQuestion
  }
}

// 问卷相关逻辑
const usePaperEffect = (token: string, id: string) => {
  const router = useRouter()
  const spinning = ref<boolean>(false)
  const updateCount = ref<number>(0)
  const paper: PaperData = reactive({
    title: '', //问卷标题
    start_time: '', //开始时间
    end_time: '', //截止时间
    status: undefined, //状态
    questions: [
      {
        number: undefined, //题号
        is_require: true, //是否必填
        questionType: 1, //问题类型：1.单选题 2.多选题 3.填空题
        questionTitle: '', //问题描述
        questionOption: ['', ''] //问题选项，填空题无元素，选择题必须包含两个以上元素
      }
    ]
  })
  const { putData } = useHttpRequestEffect(token, id, paper)
  // 监视paper数据的变动
  watch(paper, () => {
    updateCount.value++
  })
  const publishPaper = () => {
    if (updateCount.value > 1) {
      paper.questions.forEach((questionsItem, index) => {
        questionsItem.number = index + 1
      })
      // console.log(toRaw(paper));
      let isFilled = false
      if (paper.title && paper.start_time && paper.end_time) {
        paper.questions.forEach((item) => {
          if (item.number && item.questionType && item.questionTitle) {
            isFilled = item.questionOption.every((option) => option !== '')
          } else {
            isFilled = false
          }
        })
      } else {
        isFilled = false
      }
      if (isFilled) {
        Modal.confirm({
          title: '你确定问卷内容无误?',
          icon: createVNode(ExclamationCircleOutlined),
          async onOk() {
            await putData()
            spinning.value = !spinning.value
            setTimeout(() => {
              spinning.value = !spinning.value
              router.push({ name: 'paperList' })
            }, 1000)
          }
        })
      } else {
        message.warn('问卷相关信息未编辑完成')
      }
    } else {
      spinning.value = !spinning.value
      setTimeout(() => {
        spinning.value = !spinning.value
        router.push({ name: 'paperList' })
      }, 1000)
    }
  }
  return { spinning, paper, publishPaper }
}

// 网络请求逻辑
const useHttpRequestEffect = (token: string, id: string, paper: PaperData) => {
  const router = useRouter()
  const getData = async () => {
    const getRes: any = await get(`/admin/api/v1/paper/${id}`, token)
    if (getRes.code === 0) {
      paper.title = getRes.data.title
      paper.start_time = getRes.data.start_time
      paper.end_time = getRes.data.end_time
      paper.status = getRes.data.status
      paper.questions = getRes.data.questions
      console.log(paper)
    } else {
      message.error('请求错误，正在返回')
      setTimeout(() => {
        router.push({ name: 'paperList' })
      }, 1000)
    }
  }
  const putData = async () => {
    const putRes: any = await put(`/admin/api/v1/paper/${id}`, toRaw(paper), token)
    if (putRes.status_code === 0) {
      console.log(toRaw(paper))
      console.log(putRes.status_msg)
      message.success('修改成功')
    } else {
      message.error('修改失败')
    }
  }
  return { getData, putData }
}

export default defineComponent({
  components: {
    PaperTop,
    QuestionsItem,
    GoBack
  },
  setup() {
    const route = useRoute()
    const id = route.params.id as string
    const token = localStorage.getItem('token') as string
    const { spinning, paper, publishPaper } = usePaperEffect(token, id)
    const { changeTitle, changeStatus, changeStartTime, changeEndTime } = useChangeEffect(paper)
    const { addQuestion, deleteQuestion } = useEmitEffect(paper, token)
    const { getData } = useHttpRequestEffect(token, id, paper)

    onMounted(() => {
      getData()
    })

    return {
      paper,
      publishPaper,
      spinning,
      changeTitle,
      changeStatus,
      changeStartTime,
      changeEndTime,
      addQuestion,
      deleteQuestion
    }
  }
})
</script>

<style lang="less" scoped>
.title {
  text-align: center;
  font-weight: bold;
  font-size: 35px;
  padding: 20px 0 35px 0;
}
.content {
  padding: 20px 20px 0 20px;
}
</style>
